<?php require_once('assets/tool/01_function.php'); ?>
<?php

class ProductController extends AdminController
{
/**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    //public $layout='//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array("allow", // allow authenticated user to perform 'create' and 'update' actions
                "actions"    => array("index","list","listdetail","edit","delete","save","UploadImage","UploadMultiImage", "DeleteFile"),
                "users" => array("@"),
                "expression" => "Yii::app()->user->authority == Account::ADMIN"
            ),

            array("deny",  // deny all users
                "users" => array("*"),
            )
        );
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $this->render("index");
    }

    public function actionList()
    {
        $this->renderPartial("list");
    }

    public function actionListdetail()
    {
        //$dataProvider=new CActiveDataProvider('Index');
        $i_amountPerPage    = $_REQUEST["amountPerPage"];
        $i_page             = $_REQUEST["page"];
        $s_filter           = $_REQUEST["txt_filter"];
        $s_columnName       = $_REQUEST["columnName"];
        $s_sortMethod       = $_REQUEST["sortMethod"];
        
        //prepare where statement
        $s_where = "(
            pro.`subject` LIKE '%".$s_filter."%' OR
            pro.`description` LIKE '%".$s_filter."%' 
        )";
        //prepare order statement
        $s_order = "`".$s_columnName."` ".$s_sortMethod;
        
        $i_total = Yii::app()->db->createCommand("Select Count(*) from `product` pro where ".$s_where.";")->queryScalar();;
        
        $arr_model = $this->getAllList($i_page, $i_amountPerPage, $s_order, $s_where);
        
        $this->renderPartial(
            "listdetail",
            array(
                "arr_data"            => $arr_model,
                "i_totalItem"        => $i_total,
                "i_amountPerPage"    => $i_amountPerPage,
                "i_currentPage"        => $i_page
            )
        );
    }

    public function actionEdit()
    {
        //Init parameter to sent to View
        $o_model        = null;
        $o_CategoryDB   = null;
        $i_key          = null;
        $s_errMsg       = null;
        $arr_errCode    = array();
        $arr_proImage   = array();

        if( !isset($_POST["i_key"]) )
        {
            $i_key            = 0;
            $o_error          = new ErrorEntity();
            $o_error->errCode = "ERR_3";
            $o_error->param   = null;
            array_push($arr_errCode, $o_error);
        }
        else
            $i_key = $_POST["i_key"];

        $o_CategoryDB = new CActiveDataProvider("Category");

        //Get Product Object if there are product ID
        if ($i_key > 0)
        {
            $o_model = Product::getDataByID($i_key);
            if( ErrorEntity::isErrorEntity($o_model) )
            {
                array_push($arr_errCode, $o_model);
                $o_model = null;
            }
        }//End if check to get product

        //Get images of product if there are product object
        if ( $i_key > 0 && is_null($o_model) == false ) 
        {
            $arr_proImage = ProductImage::getDataByProductID($i_key);
            if( ErrorEntity::isErrorEntity($arr_proImage) )
            {
                array_push($arr_errCode, $arr_proImage);
                $arr_proImage = null;
            }
        }//End if check to get image of product

        //Set error message if there are errors
        if (count($arr_errCode) > 0 )
        {
            $s_errMsg = self::getErrorMessage($arr_errCode);
        }

        $this->renderPartial(
                "edit",
                array(
                    "o_model"      => $o_model,
                    "i_key"        => $i_key,
                    "arr_data"     => $o_CategoryDB->data,
                    "arr_proImage" => $arr_proImage,
                    "s_errMsg"     => $s_errMsg
                )
        );
    }//End actionEdit


    /** actionUploadMultiImage =========================
     * @author   TuanNguyen
     * @desc     Upload Multi Image of product to current server
     *           
     * @param    
     * @return   JSON array
     * ============================================== */
    public function actionUploadMultiImage()
    {
        if( isset($_REQUEST["token"]) == false      ||
            isset($_REQUEST["timestamp"]) == false  ||
            empty($_FILES) == true )
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_3";
            $o_error->param     = null;
            $s_errorMessage     = self::getErrorMessage($o_error);
            $arr_temp           = array("error" => $s_errorMessage);
            exit(json_encode($arr_temp));
        }

        //Init request parameter
        $s_verifyToken   = md5("unique_salt".$_REQUEST["timestamp"]);
        $s_token         = $_REQUEST["token"];

        $s_folderPath    = "images/image_product";
        $i_imgWidth      = 704;

        if ($s_token != $s_verifyToken)
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_7";
            $o_error->param     = null;
            $s_errorMessage     = self::getErrorMessage($o_error);
            $arr_temp           = array("error" => $s_errorMessage);
            exit(json_encode($arr_temp));
        }

        // Validate the file type
        $arr_types = array('jpg','jpeg','gif','png');

        $arr_result = uploadImageAjax($arr_types, "Filedata", $s_folderPath, $i_imgWidth, null);
        if( is_array($arr_result) == true )
            exit(json_encode($arr_result));
        else
        {
            $arr_result = array("result" => $arr_result);
            exit(json_encode($arr_result));
        }

        Yii::app()->end();
    }//End actionUploadMultiImage


    /** actionDeleteFile =============================
     * @author   TuanNguyen
     * @desc:    When user click button btn_deleteImage
     *           delete image file from current server
     * @return:  boolean
     * ============================================== */
    public function actionDeleteFile()
    {
        if( isset($_REQUEST["s_imgName"]) == false ||
            isset($_REQUEST["item_key"])  == false )
        {
            $o_error             = new ErrorEntity();
            $o_error->errCode    = "ERR_3";
            $o_error->param      = null;
            $s_errorMessage      = self::getErrorMessage($o_error);
            exit($s_errorMessage);
        }

        if( $_REQUEST["s_imgName"] == "" )
        {
            $o_error             = new ErrorEntity();
            $o_error->errCode    = "ERR_5";
            $o_error->param      = array("fieldName"=>"image name");
            $s_errorMessage      = self::getErrorMessage($o_error);
            exit($s_errorMessage);
        }

        if( $_REQUEST["item_key"] == "" ||
            is_numeric($_REQUEST["item_key"]) == false )
        {
            $o_error             = new ErrorEntity();
            $o_error->errCode    = "ERR_5";
            $o_error->param      = array("fieldName"=>"image name");
            $s_errorMessage      = self::getErrorMessage($o_error);
            exit($s_errorMessage);
        }

        //Init request parameter
        $i_key            = $_REQUEST["item_key"];
        $s_imgFileName    = $_REQUEST["s_imgName"];
        $s_imgFolder      = realpath("images/image_product");
        $b_isHasFile      = is_readable($s_imgFolder."\\".$s_imgFileName);

        if($b_isHasFile)
        {
            //check if there are image record in database, and delete record
            if ($i_key > 0 )
            {
                $s_where    = "`identification` = ".$i_key;
                $b_result   = ProductImage::deleteData($s_where);

                if( ErrorEntity::isErrorEntity($b_result) )
                {
                    $s_errorMessage = self::getErrorMessage($b_result);
                    exit($s_errorMessage);
                }
            }

            unlink($s_imgFolder."\\".$s_imgFileName);
            exit("1");
        }
        else
        {
            $o_error             = new ErrorEntity();
            $o_error->errCode    = "ERR_3";
            $o_error->param      = null;
            $s_errorMessage      = self::getErrorMessage($o_error);
            exit($s_errorMessage);
        }

        Yii::app()->end();
        return true;
    }

    public function actionSave()
    {
        $o_result = self::checkSaveParamRequest();
        if( ErrorEntity::isErrorEntity($o_result) )
        {
            $s_errorMessage = self::getErrorMessage($o_result);
            exit(json_encode(array( "error" => $s_errorMessage)));
        }

        $i_itemKey        = $_REQUEST["item_key"];
        $i_category       = $_REQUEST["sl_category"];
        $s_subject        = $_REQUEST["txt_subject"];
        $s_image          = $_REQUEST["txt_image"];
        $s_description    = $_REQUEST["ta_description"];
        $s_content        = $_REQUEST["ta_content"];
        $s_urlMapping     = $_REQUEST["txt_urlMapping"];
        $b_vat            = $_REQUEST["chk_vat"];
        $arr_imgURL       = $_REQUEST["arr_imgUrl"];
        $arr_imgName      = $_REQUEST["arr_imgName"];
        $date_insert      = new DateTime();

        $o_product = new Product();
        $o_product->unsetAttributes();

        $o_product->key            = $i_itemKey;
        $o_product->category       = $i_category;
        $o_product->subject        = $s_subject;
        $o_product->image          = $s_image;
        $o_product->description    = $s_description;
        $o_product->content        = $s_content;
        $o_product->url_mapping    = $s_urlMapping;
        $o_product->vat            = $b_vat;

        //Set SQL staement to insert multi-record to product_image
        $s_proImgStatement = null;
        if ( is_array($arr_imgURL)  == true &&
             is_array($arr_imgName) == true )
        {
            //add value to staement to prepare multi insert to database
            for ($i=0; $i<count($arr_imgURL); $i++)
            {
                $s_proImgStatement .= "(productKey, '".$arr_imgName[$i]."', '".$arr_imgURL[$i]."', '".$arr_imgName[$i]."', NULL, '".$date_insert->format("Y-m-d H:i:s")."'),";
            }
            //Remove last comma in statement
            $s_proImgStatement = substr($s_proImgStatement, 0, -1);
        }//end if

        //Add record
        if( $i_itemKey  == 0)
        {
            $b_result = Product::addDataToDb($o_product, $s_proImgStatement);
            if( ErrorEntity::isErrorEntity($b_result) )
            {
                $s_errorMessage = self::getErrorMessage($b_result);
                exit(json_encode(array( "error" => $s_errorMessage)));
            }

            if ($b_result == true ) {
                //print JSON Encode to view
                exit(json_encode(array( "result" => "1")));
            }
            else 
            {
                $o_error            = new ErrorEntity();
                $o_error->errCode   = "ERR_1";
                $o_error->param     = null;
                $s_errorMessage     = self::getErrorMessage($o_error);
                exit(json_encode(array( "error" => $s_errorMessage)));
            }
        }//End if add record
        //Update record
        else
        {
            $o_result = Product::updateDataToDb($o_product, $s_proImgStatement);
            if( ErrorEntity::isErrorEntity($o_result) )
            {
                $s_errorMessage = self::getErrorMessage($o_result);
                exit(json_encode(array( "error" => $s_errorMessage)));
            }
            
            exit(json_encode($o_result->getAttributes(array("key","subject","category_name","price","vat","insert"))));
        }//End else
        Yii::app()->end();
    }
    
    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete()
    {
        $arr_deleteId     = $_REQUEST["arr_deleteId"];
        
        if(is_array($arr_deleteId) == true) {
        
            $s_where        = "";
            
            foreach ($arr_deleteId as $value) {
                $s_where .= "`identification` = ".$value["value"]." OR ";
            }
        
            $s_where    = substr($s_where, 0, -3);
            
            $command = Yii::app()->db->createCommand("CALL product_05_delete (:in_where)");  
            $command->bindValue("in_where",$s_where);
            $s_result = $command->execute(); 
            
            if( $s_result >= 0) {
                
                $arr_result = array("result" => $s_result);
                exit(json_encode($arr_result));
            }
            else {
                
                $arr_error = array("error" => "Đã có lỗi với quá trình xoá, xin hãy nhấn F5 để thử lại:".$s_result);
                exit(json_encode($arr_error));
            }
        
        } else {
            
            $arr_error = array("error" => "Bạn phải chọn một dòng để xoá.");
            exit(json_encode($arr_error));
        }
    }
    
    
    public function actionUploadImage()
    {
        $o_fileInputName = $_REQUEST["fileInputName"];
        $s_destinationFolder = $_REQUEST["url_image"];
        $i_width = $_REQUEST["width_image"];
        $i_height = $_REQUEST["height_image"];
        
        $arr_types = array('jpg','jpeg','gif','png');
        
        $arr_result =  uploadImageAjax($arr_types, $o_fileInputName, $s_destinationFolder, null, $i_height);
         
        if( is_array($arr_result) == true)
        {
            exit(json_encode($arr_result));
        }
        else
        {
            $arr_result = array("result" => $arr_result);
            exit(json_encode($arr_result));
        }
        Yii::app()->end();
    }


    protected function getAllList($i_page,$i_amountPerPage,$s_order,$s_where)
    {
        $command = Yii::app()->db->createCommand("CALL product_01_getList(:p_page,:p_amount,:p_oder,:p_where)");  
        $command->bindValue("p_page",$i_page);
        $command->bindValue("p_amount",$i_amountPerPage);
        $command->bindValue("p_oder",$s_order);
        $command->bindValue("p_where",$s_where);

        $arr_model = array();
        $arr_data = $command->queryAll();

        foreach ( $arr_data as $key => $row)
        {
            $m_model = new Product();
            $m_model->unsetAttributes();

            $m_model->identification = $row["identification"];
            $m_model->key = $row["identification"];
            $m_model->category = $row["category"];
            $m_model->category_name = $row["category_name"];
            $m_model->subject = $row["subject"];
            $m_model->image = $row["image"];
            $m_model->price = $row["price"];
            $m_model->vat = $row["vat"];
            $m_model->description = $row["description"];
            $m_model->content= $row["content"];
            $m_model->url_mapping = $row["url_mapping"];
            $m_model->note = $row["note"];
            $m_model->insert = $row["insert"];
            $m_model->update = $row["update"];
            $m_model->delete = $row["delete"];

            array_push($arr_model, $m_model);
        }//End foreach

        return $arr_model;
    }


    /** checkSaveParamRequest =========================
     * @author   TuanNguyen
     * @desc     Check request param when user press btn_saveImage
     *           set reference parameter if there are an error
     * @param    
     * @return   null or ErrorEntity
     * ============================================== */
    private function checkSaveParamRequest()
    {
        $o_error = new ErrorEntity();

        if( isset($_REQUEST["item_key"])          == false ||
            isset($_REQUEST["sl_category"])       == false ||
            isset($_REQUEST["txt_subject"])       == false ||
            isset($_REQUEST["txt_image"])         == false ||
            isset($_REQUEST["ta_description"])    == false ||
            isset($_REQUEST["ta_content"])        == false ||
            isset($_REQUEST["txt_urlMapping"])    == false ||
            isset($_REQUEST["chk_vat"])           == false )
        {
            $o_error->errCode   = "ERR_3";
            $o_error->param     = null;
            return $o_error;
        }

        if ( is_numeric($_REQUEST["item_key"]) == false)
        {
            $o_error->errCode   = "ERR_4";
            $o_error->param     = array("fieldName"=>"item key", "formatName"=>"interger");
            return $o_error;
        }

        if ( is_numeric($_REQUEST["sl_category"]) == false)
        {
            $o_error->errCode   = "ERR_4";
            $o_error->param     = array("fieldName"=>"item category", "formatName"=>$_REQUEST["sl_category"]);
            return $o_error;
        }

        if ( $_REQUEST["chk_vat"] != 0 && $_REQUEST["chk_vat"] != 1 )
        {
            $o_error->errCode   = "ERR_4";
            $o_error->param     = array("fieldName"=>"item VAT", "formatName"=>"boolean");
            return $o_error;
        }

        if (strlen($_REQUEST["txt_subject"]) <= 4) 
        {
            $o_error->errCode   = "ERR_8";
            $o_error->param     = array("fieldName"=>"item name", "stringLength"=>"4");
            return $o_error;
        }

        if ( isset($_REQUEST["arr_imgUrl"]) == false )
        {
            $_REQUEST["arr_imgUrl"] = null;
        }
        else 
        {
            if( !is_array($_REQUEST["arr_imgUrl"]) )
            {
                $o_error->errCode   = "ERR_4";
                $o_error->param     = array("fieldName"=>"image urls", "formatName"=>"array");
                return $o_error;
            }

            if( count($_REQUEST["arr_imgUrl"]) < 1 )
            {
                $o_error->errCode   = "ERR_5";
                $o_error->param     = array("fieldName"=>"Image Url List");
                return $o_error;
            }
        }

        if ( isset($_REQUEST["arr_imgName"]) == false )
        {
            $_REQUEST["arr_imgName"] = null;
        }
        else
        {
            if( !is_array($_REQUEST["arr_imgName"]) )
            {
                $o_error->errCode   = "ERR_4";
                $o_error->param     = array("fieldName"=>"image names", "formatName"=>"array");
                return $o_error;
            }

            if( count($_REQUEST["arr_imgName"]) < 1 )
            {
                $o_error->errCode   = "ERR_5";
                $o_error->param     = array("fieldName"=>"image names");
                return $o_error;
            }
        }

        return null;
    }


    /** getErrorMessage =============================
     * @author   TuanNguyen
     * @desc     get error message from array of error entity
     *           set reference parameter if there are an error
     * @param    $errorEnts: array of error entity or error entity
     * @return   string: error message
     * ============================================== */
    private function getErrorMessage($errorEnts)
    {
        $arr_errorMessage    = array(
                "ERR_1" => "There are an error with parameters in SQL statement. ",
                "ERR_2" => "SQLException",
                "ERR_3" => "Recieved Parameter is wrong or missing. ",
                "ERR_4" => "format of fieldName is formatName, please type value as formatName format . ",
                "ERR_5" => "fieldName is empty, please set value for it. ",
                "ERR_6" => "ImageType don't exist in image configuration. ",
                "ERR_7" => "There are another opened tab or browser require this function. ",
                "ERR_8" => "string length of fieldName is over stringLength. "
        );
    
        //Return error message
        if ( is_array($errorEnts) )
        {
            return ErrorEntity::setErrorMessageByArray($errorEnts, $arr_errorMessage);
        }
        elseif ( $errorEnts instanceof ErrorEntity )
        {
            return ErrorEntity::setErrorMessageByEntity($errorEnts, $arr_errorMessage);
        }
    }
}